package com.agileai.miscdp.hotweb.ui.actions;

import java.net.URL;

import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.browser.IWebBrowser;
import org.eclipse.ui.browser.IWorkbenchBrowserSupport;

import com.agileai.miscdp.hotweb.ConsoleHandler;
import com.agileai.miscdp.hotweb.domain.ProjectConfig;
import com.agileai.miscdp.util.MiscdpUtil;

public class OpenBrowserAction implements IObjectActionDelegate{
    private IWorkbenchPart targetPart;  
    
	public void run(IAction action) {
		ISelection selection = targetPart.getSite().getSelectionProvider().getSelection();
		IStructuredSelection curSelection = (IStructuredSelection)selection;
		IJavaProject javaProject = (IJavaProject)curSelection.getFirstElement();
		try {
			String appName = javaProject.getElementName();
		    IWorkbenchBrowserSupport support = PlatformUI.getWorkbench().getBrowserSupport();
		    IWebBrowser browser = support.createBrowser("OpenWebsite");
		    ProjectConfig projectConfig = MiscdpUtil.getProjectConfig(appName);
		    String serverPort = projectConfig.getServerPort();
		    browser.openURL(new URL(("http://localhost:"+serverPort+"/"+appName)));
		} catch (Exception e) {
			ConsoleHandler.error(e.getLocalizedMessage());
		}
	}

	public void setActivePart(IAction action, IWorkbenchPart workbenchPart) {
        this.targetPart = workbenchPart;  
	}
	public void selectionChanged(IAction action, ISelection selection) {
	}	
}